#!/usr/bin/node
const EventEmitter = require('events').EventEmitter;

function MusicPlayer(track) {
  this.track = track;
  //默认播放状态
  this.playing = false;
  //遍历EventEmitter.prototype的所有的函数
  for (let methodName in EventEmitter.prototype) {
    console.log(methodName);
    //将函数名称放到对应的EventEmitter的原型函数对象里
    this[methodName] = EventEmitter.prototype[methodName];
  }
}

//对MusicPlayer对象的toString函数实现重载

MusicPlayer.prototype = {
  toString: function () {
    if (this.playing) {
      return "Now Playing:" + this.track;
    } else {
      return 'Stopped';
    }
  }
};

let musicPlayer = new MusicPlayer('storm');

//play事件
musicPlayer.on('play', function () {
  this.playing = true;
  console.log('\n', this.toString());
});

//stop事件
musicPlayer.on('stop', function () {
  this.playing = false;
  console.log('\n', this.toString());
});

//事件发生
musicPlayer.emit('play');

//事件2秒后停止
setTimeout(function () {
  musicPlayer.emit('stop');
}, 2000)

